package com.smh.aiagent.tools;

import com.smh.aiagent.mapper.UserInfoMapper;
import com.smh.aiagent.mapper.UserMapper;
import com.smh.aiagent.template.MinioTemplate;
import jakarta.annotation.Resource;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.ToolCallbacks;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;

@Configuration
public class ToolRegistration {

    @Value("${custom.search.api}")
    private String searchApiKey;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from; // 发件人邮箱
    @Resource
    private MinioTemplate minioTemplate;

    @Resource
    private ToolCallbackProvider mcpToolCallbacks;

    @Bean
    public ToolCallback[] allTools() {
        FileOperationTool fileOperationTool = new FileOperationTool();
        WebSearchTool webSearchTool = new WebSearchTool(searchApiKey);
        WebScrapingTool webScrapingTool = new WebScrapingTool();
        ResourceDownloadTool resourceDownloadTool = new ResourceDownloadTool();
        TerminalOperationTool terminalOperationTool = new TerminalOperationTool();
        PDFGenerationTool pdfGenerationTool = new PDFGenerationTool();
        CustomerTool customerTool = new CustomerTool(userMapper, userInfoMapper);
        SendEmailTool sendEmailTool = new SendEmailTool(mailSender, from);
        FileUploadTool fileUploadTool = new FileUploadTool(minioTemplate);
        TerminateTool terminateTool = new TerminateTool();
        AskHumanTool askHumanTool = new AskHumanTool();
        ToolCallback[] toolCallbacks = ToolCallbacks.from(
                fileOperationTool,
                webSearchTool,
                webScrapingTool,
                resourceDownloadTool,
                terminalOperationTool,
                pdfGenerationTool,
                customerTool,
                sendEmailTool,
                fileUploadTool,
                terminateTool,
                askHumanTool);

        ToolCallback[] mcpToolCallbackArray = (ToolCallback[]) mcpToolCallbacks.getToolCallbacks();
        // 合并mcp和自定义工具
        ToolCallback[] allToolCallbacks = new ToolCallback[toolCallbacks.length + mcpToolCallbackArray.length];
        System.arraycopy(toolCallbacks, 0, allToolCallbacks, 0, toolCallbacks.length);
        System.arraycopy(mcpToolCallbackArray, 0, allToolCallbacks, toolCallbacks.length, mcpToolCallbackArray.length);

        return allToolCallbacks;
    }
}
